/*************************************************
 *FileName:      myfriends.js
 *Description:   查看朋友圈.js
 *Others:        陈灿
 *************************************************/
    /*
     * 启动
     */
    mui.init();
    mui('.mui-scroll-wrapper').scroll({
        indicators: false,      //是否显示滚动条 默认为true
        deceleration: 0.003,    //阻尼系数,系数越小滑动越灵敏 默认0.0006
        bounce: true           //是否启用回弹 默认true
    });
    /*
     * 变量初始化
     */
    var that = getUrlParam('this');
    var uid = localStorage.replace_uid;
    var friend_uid = getUrlParam('friend_uid');
    var token = localStorage.replace_token;
    var page = 1;
    var page_num = 5;
    var isUp = true;
    var orderopen=true;
    /*
     * HTML5+准备完成
     */
    window.addEventListener('circlefriends', function(e){//执行刷新
        $('.main').html('');
        isUp = true;
        page = 1;
        getArticles();
    });
    
    mui.plusReady(function(){ 
        var wv=plus.webview.currentWebview();// 关闭侧滑返回功能
        wv.setStyle({'popGesture':'none'});
        var old_back = mui.back;
        mui.back = function() {
            if(orderopen==true){
                old_back();
            }else{
                orderopen=true;
                $('.circlefriendsimg').css({display:'none'});
                $('#video')[0].pause();
            }
        }
    });
    
    /*
     * 主程序
     */ 
    $(document).ready(function() 
    {
        //样式加载
        pagecss();
    });
    /**
     * pagecss
     * 样式加载
     * @cc 
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int        
     * @return   void
     */
    function pagecss(){
        mui.plusReady(getArticles)
//      getArticles();
        common.format();
        if(that){
            $('.mui-title-box').text('朋友圈');
            $('.icon-right').addClass('header-menu header-menu2');
            $('.circlefriendsimg .header-menu').on('tap',function(){
                $('.menu-click2').fadeIn();
                $('.popover-img').show();
            })//朋友圈图片预览菜单显示
            $.ajax({
                type: "post",
                url: DOMAIN_NAME + "/index.php/api/user/othersInfo",
                dataType:'jsonp',
                data: { uid:friend_uid},
                success: function(data) {
                    if(data.error_code == 0){
                        data.data.img ? $('.title-bg').css('background-image','url('+DOMAIN_NAME+data.data.img+')'):$('.title-bg').css('background-image','url(images/fd_bj.png)');
                        $('.my-img').attr('src',DOMAIN_NAME+data.data.face);
                        $('.my-name').html(data.data.nickname);
                    }else if(data.error_code == 1001){
                        setTimeout(function(){
                            exitlogin();
                        },1000);
                    }
                }
            });
        }else{
            $('.mui-title-box').text('我的朋友圈');
            $('.icon-right').addClass('camera');
            $('.circlefriendsimg .header-menu').on('tap',function(){
                $('.menu-click3').fadeIn();
                $('.popover-img').show();
            })//朋友圈图片预览菜单显示
            localStorage.replace_myimg ? $('.title-bg').css('background-image','url('+DOMAIN_NAME+localStorage.replace_myimg+')'):$('.title-bg').css('background-image','url(images/fd_bj.png)');
            $('.my-img').attr('src',DOMAIN_NAME+localStorage.replace_face);
            $('.my-name').html(localStorage.replace_nickname);
        }

        $('.table-view-cell-cancel').on('tap',function(){
            if($(this).hasClass('sure')){
                var report_content = [];
                var i = 0;
                $('.table-select').each(function(){
                    if($(this).hasClass('active')){
                        report_content[i] = $(this).text();
                        i++;
                    }
                })
                if(!report_content){
                    mui.toast('请选择您要举报的内容！',{ duration:2000, type:'div' });
                    return false;
                }
                $.ajax({
                    type: "post",
                    url: DOMAIN_NAME + "/index.php/api/report/reportAdd",
                    dataType:'jsonp',
                    data: { uid: uid, token: token, report_uid: friend_uid, report_content: report_content, type: 1 },
                    success: function(data) {
                        if(data.error_code == 0){
                            mui.toast('举报成功！',{ duration:2000, type:'div' });
                        }else if(data.error_code == 1001){
                            setTimeout(function(){
                        exitlogin();
                    },1000);
                        }else{
                            mui.toast('举报失败！',{ duration:2000, type:'div' });
                        }
                    }
                });

            }
            $('.table-select').removeClass('active');
            $('.popover').fadeOut();
            $('.table-view').fadeOut();
        })//下拉菜单栏取消
        
        $('.complains').on('tap',function(){
            $('.menu-click').css({display:'none'});
            $('.table-view2').fadeIn();
        })//举报
        
        $('.circlefriends').on('tap','.table-view2 .table-view-cell-a',function(){
            $(this).toggleClass('active');
        })//举报选项效果
        
        $('.save-this').on('tap',function(){
            var src = $('#slider').find('.mui-active').children('a').children('img').attr('src');
            if(!src){
                src = $('#slider .mui-slider-item').eq(0).children('a').children('img').attr('src');
            }
            plus.nativeUI.showWaiting('Downloading');
            var url = src;//下载链接
            var options = {
                method: "GET",//get传输方式
                filename: '_doc/'//文件保存位置
            };
            var dtask = plus.downloader.createDownload(src, {}, function(download, status) {
                if ( status == 200 ) { 
                    plus.nativeUI.closeWaiting();
                    plus.gallery.save(download.filename, function() {
                        mui.toast('Save successfully');
                    });
                } else {
                    alert( "Download failed: " + status ); 
                }
            });
            dtask.start();
        })//保存图片

        $('.black').on('tap',function(){
            $('.menu-click2').css('display','none');

            blackAdd();
        })
        function blackAdd(){
            mui.confirm('确定要屏蔽她的朋友圈?','<div class="promit-msg">提示</div>',['确定','取消'],function(e){
                $('.popover').fadeOut();
                if(e.index == 0){
                    $.ajax({
                        type: "post",
                        url: DOMAIN_NAME + "/index.php/api/user/blacklistAdd",
                        dataType:'jsonp',
                        data: { uid: uid, token: token, black_uid: friend_uid },
                        success: function(data) {
                            if(data.error_code == 0){
                                mui.toast('屏蔽成功！',{ duration:2000, type:'div' });
                            }else if(data.error_code == 1001){
                                setTimeout(function(){
                        exitlogin();
                    },1000);
                            }else{
                                mui.toast(data.error_msg,{ duration:2000, type:'div' });
                                black_uid = '';
                            }
                        }
                    }); 
                    
                }
            },'div');
        }
        
        $('.delect-this').on('tap',function(){
            $('.menu-click3').css({display:'none'});
            $('.popover-img').css({display:'none'});
            var article_id = $(this).attr('data-id');
            mui.confirm('确定要删除这条朋友圈吗？','提示',['确定','取消'],function(e){
                if(e.index == 0){
                    $.ajax({
                        type: "post",
                        url: DOMAIN_NAME + "/index.php/api/article/articleDel",
                        dataType:'jsonp',
                        data: { uid: uid, token: token, article_id: article_id },
                        success: function(data) {
                            if(data.error_code == 0){
                                $('.circlefriendsimg').css({display:'none'});
                                orderopen=true;
                            }else if(data.error_code == 1001){
                                setTimeout(function(){
                        exitlogin();
                    },1000);
                            }else{
                                mui.toast('删除失败！',{ duration:2000, type:'div' });
                            }
                        }
                    }); 
                }
            },'div');
        })//删除动态

        $('.circlefriends .camera').on('tap',function(){
            $('.popover').fadeIn();
            $('.table-view3').fadeIn();
        })//朋友圈点击相机
    
        $('.table-view-cell-cancel').on('tap',function(){
            $('.popover').fadeOut();
            $('.table-view').fadeOut();
            $('.popover-img').css({display:'none'});
        })//下拉菜单栏取消
        
        $('.circlefriendsimg .mui-slider').on('tap','.mui-slider-item',function(){
            $('.circlefriendsimg header.header-color').slideToggle();
            $('.circlefriendsimg footer.friendsimg-footer .ft-bottom').slideToggle();
        })//朋友圈图片预览点击图片头部底部消失
        //待优化
        $('.mui-action-return').on('tap',function(){
            $('.circlefriendsimg').css({display:'none'});
            orderopen=true;
            $('#video')[0].pause();
        })//图片返回
        
        $('.popover-img').on('touchend',function(){
            $('.menu-click').fadeOut();
            $('.table-view').fadeOut();
            $(this).hide();
        })//朋友圈图片预览点击图片头部底部消失
        
        $('.myfriends .popover').on('tap',function(){
            $('.menu-click').hide();
            $(this).hide();
        })//朋友圈点击头部底部消失
        
        
        $('.header-menu2').on('tap',function(){
            $('.menu-click1').fadeIn();
            $('.popover-img').show();
        })//朋友圈菜单显示
        
        $('.circlefriendsimg .btn-link').on('tap',function(){
            var article_id = $(this).parent().attr('data-id');
            common.pageTransition('particulars.html?id='+article_id)
            $('.circlefriendsimg').css({display:'none'});
            orderopen=true;
        })//朋友圈图片预览菜单显示
        
        $('.main').on('tap','.inf',function(){
            if($(this).find('img').length<1){
                var article_id = $(this).attr('data-id');
                common.pageTransition('particulars.html?id='+article_id)
                return false;
            }
            var is_like = '';
            var art_id = $(this).attr('data-id')
            var content = $(this).find('.inf-text-p').text();
            if($(this).attr('data-isLike') > 0){
                $('.btn-like').addClass('onlike');
            }else{
                $('.btn-like').removeClass('onlike');
            }
            var comment_nums = $(this).attr('data-commentNums');
            var like_nums = $(this).attr('data-likeNums');
            var pub_time = $(this).attr('data-pubTime');
            
            $('.menu-click3 .delect-this').attr('data-id',art_id);
            $('.ft-bottom').attr('data-id',art_id);
            $('.circlefriendsimg .mui-title').html(pub_time);
            $('.footer-text').html(content);
            $('.btn-like').addClass(is_like);
            $('.comment-nums').html(comment_nums);
            $('.like-nums').html(like_nums);
            var imgs = '';
            if($(this).find('.inf-video').length>0){
                imgs += '<div class="mui-slider-item active"><a href="javascript:"><video id="video" src="'+$(this).find('img').attr("data-url")+'"></video></a></div>'
            }else{
                $(this).find('img').each(function(){
                    imgs += '<div class="mui-slider-item active"><a href="javascript:"><img src="'+$(this).attr("data-url")+'"/></a></div>'
                })
            }
            $('.circlefriendsimg .mui-slider-group').html(imgs);
            if($(this).find('.inf-video').length>0){
                $('#video')[0].play();
            }
            mui('#slider').slider({
                interval:0//自动轮播周期，若为0则不自动播放，默认为0；
            });
            $('.circlefriendsimg').css({display:'block'});
            orderopen=false;
        })//朋友圈li点击跳转详情
        
        $('.myfriends .inf-img').each(function(){
            if($(this).find('img').length>3){
                $(this).addClass('img-first');
            }else if($(this).find('img').length==3){
                $(this).addClass('img-second');
            }else if($(this).find('img').length==2){
                $(this).addClass('img-thirdly');
            }else if($(this).find('img').length==1){
                $(this).addClass('img-last');
            }else{
                $(this).addClass('img-null');
                $(this).next().addClass('inf-text-p-null');
            }
        })//朋友圈图片加载

        $('.circlefriendsimg .btn-like').on('tap',function(){
            var article_id = $(this).parent().attr('data-id');
            var obj = $(this);
            if(!$(this).hasClass('onlike')){
                $.ajax({
                    type: "post",
                    url: DOMAIN_NAME + "/index.php/api/article/articleLikeAdd",
                    dataType:'jsonp',
                    data: { uid: uid, token: token, article_id: article_id },
                    success: function(data) {
                        if(data.error_code == 0){
                            obj.addClass('onlike'); 
                            $('.main').find('.inf[data-id="'+article_id+'"]').attr('data-isLike','1');
                            var num = $('.like-nums').html()-0+1;
                            $('.like-nums').html(num)
                        }else if(data.error_code == 1001){
                            setTimeout(function(){
                        exitlogin();
                    },1000);
                        }else{
                            mui.toast('点赞失败！',{ duration:2000, type:'div' });
                        }
                    }
                }); 
            }else{
                $.ajax({
                    type: "post",
                    url: DOMAIN_NAME + "/index.php/api/article/articleLikeCancel",
                    dataType:'jsonp',
                    data: { uid: uid, token: token, article_id: article_id },
                    success: function(data) {
                        if(data.error_code == 0){
                            obj.removeClass('onlike');
                            $('.main').find('.inf[data-id="'+article_id+'"]').attr('data-isLike','0');
                            var num = $('.like-nums').html()-1;
                            $('.like-nums').html(num);
                        }else if(data.error_code == 1001){
                            setTimeout(function(){
                        exitlogin();
                    },1000);
                        }else{
                            mui.toast('取消点赞失败！',{ duration:2000, type:'div' });
                        }
                    }
                }); 
            }
        })
    }

    function getArticles(){
        if(friend_uid && that == 'other'){
            var url = "/index.php/api/article/getUsersArticles";
            var data = {
                uid: uid,
                token: token,
                page: page,
                page_num: page_num,
                friend_uid: friend_uid
            }
        }else{
            var url = "/index.php/api/article/getMyArticles"
            var data = {
                uid: uid,
                token: token,
                page: page,
                page_num: page_num
            }
        }
        $.ajax({
            type: "post",
            url: DOMAIN_NAME + url,
            dataType:'jsonp',
            data: data,
            success: function(data) {
                if(data.error_code == 0){
                    var li = '';
                    var imgs = '';
                    if(data.data.length == page_num){
                        $('.mui-scroll').children('.ys-scroll-btm').html('上拉加载更多');
                        isUp = true;
                    }else{
                        $('.mui-scroll').children('.ys-scroll-btm').html('已经到底了');
                        isUp = false;
                    }
                    
                    $('.mui-scroll').children('.ys-scroll-top').html('下拉刷新数据').attr('style', false);
                    for(var i=0; i<data.data.length; i++){
                        if($('.main').find('.inf[data-id="'+data.data[i].id+'"]').html()){
                        }else{
                            var is_like = data.data[i].is_like;
                            var like_nums = data.data[i].like_nums;
                            var comments_nums = data.data[i].comment_nums;
                            if(data.data[i].files){
                                var pic_num = data.data[i].files.length;
                                var files = '';
                                var file_type = '';
                                if(data.data[i].files.length==1){
                                    if(data.data[i].files[0].type == 1){
                                        files += '<img src="'+DOMAIN_NAME+data.data[i].files[0].thumb+'" data-url="'+DOMAIN_NAME+data.data[i].files[0].url+'"/>'
                                    }else{
                                        file_type = 'inf-video';
                                        files += '<img src="'+data.data[i].files[0].thumb+'" data-url="'+data.data[i].files[0].url+'"/>'
                                    }
                                }else{
                                    for(var j=0; j<pic_num; j++){
                                        files += '<img src="'+DOMAIN_NAME+data.data[i].files[j].thumb+'" data-url="'+DOMAIN_NAME+data.data[i].files[j].url+'"/>'
                                    }
                                }
                            }
                            li += '<li class="inf" data-id="'+data.data[i].id+'" data-isLike="'+is_like+'" data-likeNums="'+like_nums+'" data-commentNums="'+comments_nums+'" data-pubTime="'+new Date(data.data[i].publish_time*1000).format('yyyy-MM-dd hh:mm')+'"><div class="inf-time">'
                                +'<p class="inf-time-text">'+new Date(data.data[i].publish_time*1000).format('dd')+'</p>'
                                +'<span class="inf-time-text">'+new Date(data.data[i].publish_time*1000).format('MM')+'月</span></div>'
                                +'<div class="inf-msg"><div class="inf-img '+file_type+'">'+files+'</div><div class="inf-text">'
                                +'<p class="inf-text-p">'+data.data[i].content+'</p><p class="pages">共'+pic_num+'张</p>'
                                +'</div></div></li>'
                        }
                    }
                    $('.main').append(li);
                    $('.myfriends .inf-img').each(function(){
                        if($(this).find('img').length>3){
                            $(this).addClass('img-first');
                        }else if($(this).find('img').length==3){
                            $(this).addClass('img-second');
                        }else if($(this).find('img').length==2){
                            $(this).addClass('img-thirdly');
                        }else if($(this).find('img').length==1){
                            $(this).addClass('img-last');
                        }else{
                            $(this).addClass('img-null');
                            $(this).next().addClass('inf-text-p-null');
                        }
                    })//朋友圈图片加载
                    // var gallery = mui('.mui-slide');
                    mui('#slider').slider({
                        interval:0//自动轮播周期，若为0则不自动播放，默认为0；
                    });
                    page++;
                }else if(data.error_code == 1001){
                    setTimeout(function(){
                        exitlogin();
                    },1000);
                }else{
                    $('.mui-scroll').children('.ys-scroll-btm').html('已经到底了');
                    isUp = false;
                }
            }
        });
    }

    common.scrollUpDown($('.mui-scroll'),function(index){
        if(index>0&&isUp){
            isUp = false;
            getArticles();
        }else if(index<0){
            $('.main').html('');
            isUp = true;
            page = 1;
            getArticles();
        }else if(index>0 && !isUp){
            $('.mui-scroll').children('.ys-scroll-btm').html('已经到底了');
        }
    });

    


    